package map.android.baidu.carpool.page.home;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.entity.pb.PoiResult;
import com.baidu.mapframework.api.NewSearchCallback;
import com.baidu.mapframework.api.SearchResponce;
import com.baidu.mapframework.app.fpstack.RegisterPage;
import com.baidu.platform.comapi.basestruct.Point;
import com.baidu.platform.comapi.search.convert.PBConvertUtil;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.model.CarpoolPosition;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.preferences.SugHistoryPreferences;
import map.android.baidu.carpool.utils.HelpUtils;
import map.android.baidu.carpool.utils.LogUtils;
import map.android.baidu.carpool.utils.ToastForCarpool;
import map.android.baidu.carpool.widget.TextinputHistroyAndSugListView;
import map.android.baidu.carpool.widget.TextinputHistroyAndSugListView.TextInputSug;

import java.util.ArrayList;
import java.util.List;

@RegisterPage(taskName = "com.baidu.baidumaps.MapsActivity")
public class TextInputSugPage extends CarpoolBasePage {
    public static final String LOGTAG = "TextInputSugPage";

    public static final String KEY_PARAM_NAME = "name";
    public static final String KEY_PARAM_MYPOSITION = "myposition";
    public static final String KEY_PARAM_SUG = "sug";
    public static final String KEY_PARAM_TYPE = "type";
    public static final String KEY_PARAM_ADDRESS = "result_address";

    public static final int TYPE_FROM_WHERE = 1;
    public static final int TYPE_GO_WHERE = 2;

    private int mType = 1;

    private CarpoolPosition mMyPosition;
    private TextInputSug textInputMypositonSug;

    private View mMainSugView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if (mMainSugView == null) {
            mMainSugView = APIProxy.res().inflate(R.layout.carpool_page_textinput_sug, container, false);
        }
        try {
            initMainSugView();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mMainSugView;
    }

    private TextinputHistroyAndSugListView mSugListView;
    private EditText mWhereEditText;
    private String mName = "";
    private ImageButton mClearImageButton;
    private Button okButton;
    private ImageView searchImage;

    private void initMainSugView() {
        ImageView backImageView = (ImageView) mMainSugView.findViewById(R.id.car_btn_back);
        mWhereEditText = (EditText) mMainSugView.findViewById(R.id.car_edittext);
        mClearImageButton = (ImageButton) mMainSugView.findViewById(R.id.car_btn_delete);
        okButton = (Button) mMainSugView.findViewById(R.id.car_btn_ok);
        searchImage = (ImageView) mMainSugView.findViewById(R.id.car_serchbox_icon_imageview);
        try {
            mSugListView = (TextinputHistroyAndSugListView) mMainSugView.findViewById(R.id.car_listview);
        } catch (ClassCastException e) {
            e.printStackTrace();
        }

        Bundle bundle = getArguments();
        if (bundle != null) {
            initUIForTextInputPage(bundle);
        }
        initSugListView();

        backImageView.setOnClickListener(mOnClickListener);
        mWhereEditText.setOnClickListener(mOnClickListener);
        mClearImageButton.setOnClickListener(mOnClickListener);
        hideClearImageButton();
        okButton.setOnClickListener(mOnClickListener);

        mWhereEditText.addTextChangedListener(mWatcher);
        mWhereEditText.setFocusable(true);
        mWhereEditText.setFocusableInTouchMode(true);
        showHistory();
    }

    private void initUIForTextInputPage(Bundle bundle) {
        mType = bundle.getInt(KEY_PARAM_TYPE, 1);
        mName = bundle.getString(KEY_PARAM_NAME);
        mMyPosition = (CarpoolPosition) bundle.getSerializable(KEY_PARAM_MYPOSITION);
        if (mMyPosition != null) {
            textInputMypositonSug = new TextInputSug();
            if (!TextUtils.isEmpty(mMyPosition.name)) {
                textInputMypositonSug.setName(mMyPosition.name);
            }
            if (!TextUtils.isEmpty(mMyPosition.address)) {
                textInputMypositonSug.setAddress(mMyPosition.address);
            }
            if (mMyPosition != null) {
                // textInputMypositonSug.setPoint(mMyPosition.point);
                Point point = new Point(mMyPosition.x, mMyPosition.y);
                textInputMypositonSug.setPoint(point);
            }
        }
        int leftDrawableId = 0;
        int hintResId = 0;
        if (TYPE_FROM_WHERE == mType) {
            leftDrawableId = R.drawable.taxi_from_where;
            hintResId = R.string.car_from_where;
        } else {
            leftDrawableId = R.drawable.taxi_go_where;
            hintResId = R.string.car_go_where;
        }
        mWhereEditText.setHint(hintResId);
        mWhereEditText.setCompoundDrawablesWithIntrinsicBounds(leftDrawableId, 0, 0, 0);

        if (mSugListView != null) {
            mSugListView.setVisibility(View.VISIBLE);
        }
    }

    private void initSugListView() {
        if (mSugListView == null) {
            return;
        }

        mSugListView.setFooterClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                clearHistory();
            }
        });
        mSugListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mSugArrayList != null && position < mSugArrayList.size()) {
                    TextinputHistroyAndSugListView.TextInputSug textInputSug = mSugArrayList.get(position);
                    HelpUtils.closeSoftKeyboard(mWhereEditText);
                    clearWhereEdit();
                    goBackWithSug(textInputSug);
                }
            }
        });

        mSugListView.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(final AbsListView view, final int scrollState) {
                if (scrollState == OnScrollListener.SCROLL_STATE_FLING) {
                    HelpUtils.closeSoftKeyboard(mWhereEditText);
                }
            }

            @Override
            public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount,
                    final int totalItemCount) {
            }
        });
    }

    private TextWatcher mWatcher = new SugTextWatcher();

    class SugTextWatcher implements TextWatcher {

        @Override
        public void onTextChanged(final CharSequence sequence, final int start, final int before, final int count) {
            if (mSugListView != null) {
                mSugListView.setVisibility(View.VISIBLE);
            }
            String text = mWhereEditText.getText().toString();
            if (text == null || text.length() == 0) {
                // 显示历史记录
                // mControl.cancel();
                hideClearImageButton();
                showHistory();
                okButton.setVisibility(View.GONE);
                searchImage.setVisibility(View.VISIBLE);
            } else {
                // 显示sug
                showClearImageButton();
                searchImage.setVisibility(View.INVISIBLE);
                String word = mWhereEditText.getText().toString();
                okButton.setVisibility(View.VISIBLE);
                // getSug(word, UserInfo.getInstance().getCityId(), UserInfo
                // .getInstance().getMapLevel() + "");
                getSug(word);
            }
        }

        @Override
        public void beforeTextChanged(final CharSequence sequence, final int start, final int count, final int after) {
        }

        @Override
        public void afterTextChanged(final Editable editable) {
        }
    }

    private void hideClearImageButton() {
        if (mClearImageButton != null) {
            mClearImageButton.setVisibility(View.GONE);
        }
    }

    private void showClearImageButton() {
        if (mClearImageButton != null) {
            mClearImageButton.setVisibility(View.VISIBLE);
        }
    }

    private void showHistory() {
        if (mSugListView == null) {
            return;
        }

        ArrayList<TextinputHistroyAndSugListView.TextInputSug> historyList = getHistoryList();
        mSugArrayList.clear();
        if (textInputMypositonSug != null) {
            mSugArrayList.add(textInputMypositonSug);
        }
        if (historyList != null && historyList.size() > 0) {
            for (int i = 0; i < historyList.size(); i++) {
                TextinputHistroyAndSugListView.TextInputSug sug = historyList.get(i);
                mSugArrayList.add(sug);
            }
            mSugListView.setVisibility(View.VISIBLE);
            mSugListView.setHistoryContentList(mSugArrayList);
            if (mSugArrayList.size() < 2) {
                mSugListView.hideFooter();
            }
            return;
        } else {
            if (mSugListView != null) {
                mSugListView.setVisibility(View.VISIBLE);
                mSugListView.setHistoryContentList(mSugArrayList);
            } else {
                mSugListView.setVisibility(View.GONE);
                mSugListView.setHistoryContentList(null);
            }
        }
    }

    private void clearHistory() {
        clearPreferenceHistory();
        if (mSugListView == null) {
            return;
        }
        mSugListView.setVisibility(View.GONE);
        mSugListView.setHistoryContentList(null);
    }

    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.car_btn_back:
                    HelpUtils.closeSoftKeyboard(mWhereEditText);
                    clearWhereEdit();
                    APIProxy.navi().goBack(null);
                    break;

                case R.id.car_edittext:
                    break;

                case R.id.car_btn_delete:
                    clearWhereEdit();
                    break;

                case R.id.car_btn_ok:
                    String word = mWhereEditText.getText().toString();
                    if (!TextUtils.isEmpty(word)) {
                        getSug(word);
                        ToastForCarpool.show(getActivity(), "请从搜索结果中选择！");
                    } else {
                        TextinputHistroyAndSugListView.TextInputSug sug = new TextinputHistroyAndSugListView.TextInputSug();
                        sug.setAddress("");
                        sug.setName("");
                        sug.setPoint(null);
                        HelpUtils.closeSoftKeyboard(mWhereEditText);
                        clearWhereEdit();
                        goBackWithSug(sug);
                    }
                    break;

                default:
                    break;
            }
        }
    };

    private void clearWhereEdit() {
        if (mWhereEditText != null) {
            mWhereEditText.setText("");
        }
    }

    private void goBackWithSug(TextInputSug sug) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_PARAM_SUG, sug);
        bundle.putInt(KEY_PARAM_TYPE, mType);
        if (sug != null && sug.getPoint() != null && !TextUtils.isEmpty(sug.getName())) {
            saveSugHistory(sug);
        }

        APIProxy.navi().goBack(bundle);
    }

    private ArrayList<TextInputSug> mSugArrayList = new ArrayList<TextInputSug>();

    // 看这里：http://fe.baidu.com/doc/map/interface_api/su.text
    private void getSug(String word) {
        if (word == null) {
            word = "";
        } else {
            word = word.trim();
        }

        if (!checkNetworkStatus(true)) {
            mSugListView.setVisibility(View.GONE);
            return;
        }
        if (TextUtils.isEmpty(word)) {
            return;
        }
        APIProxy.newSearch().oneSearch(word, null, new NewSearchCallback() {

            @Override
            public void onErrorResponce(SearchResponce response) {
                if (response != null) {
                    LogUtils.w(LOGTAG, response.errorMessage);
                }
            }

            @Override
            public void onSuccessResponce(SearchResponce response) {
                try {
                    PoiResult poiResult = (PoiResult) response.messageLight;
                    List<PoiResult.Contents> list = poiResult.getContentsList();
                    mSugArrayList.clear();
                    if (textInputMypositonSug != null) {
                        mSugArrayList.add(textInputMypositonSug);
                    }
                    for (int i = 0; i < list.size(); i++) {
                        PoiResult.Contents contents = list.get(i);
                        String geo = contents.getGeo();
                        Point p = PBConvertUtil.decryptPoint(geo);
                        TextInputSug textInputSug = new TextInputSug();
                        textInputSug.setName(contents.getName());
                        textInputSug.setAddress(contents.getAddr());
                        textInputSug.setPoint(p);
                        mSugArrayList.add(textInputSug);
                        textInputSug = null;
                    }
                    if (mSugArrayList.size() > 0) {
                        if (mSugListView != null) {
                            mSugListView.setVisibility(View.VISIBLE);
                            mSugListView.setSugContentList(mSugArrayList);
                        }
                    } else {
                        showHistory();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mSugArrayList.clear();
                    showHistory();
                }
            }

        });
    }

    public void showToast(int resId) {
        if (getActivity() == null) {
            return;
        }
        Toast.makeText(getActivity(), resId, Toast.LENGTH_SHORT).show();
    }

    public void showToast(String info) {
        if (getActivity() == null) {
            return;
        }
        Toast.makeText(getActivity(), info, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (mWhereEditText != null) {
            if (mName == null) {
                mName = "";
            }
            mWhereEditText.post(new Runnable() {
                @Override
                public void run() {
                    mWhereEditText.setSelection(mWhereEditText.getText().length());
                }
            });
        }
        HelpUtils.showSoftKeyboard(mWhereEditText);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mWhereEditText != null) {
            mWhereEditText.setText(mName);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMainSugView = null;
    }

    private void saveSugHistory(TextInputSug sug) {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }

        if (mType == TYPE_FROM_WHERE) {
            SugHistoryPreferences.saveFromWhereSugHistory(activity, sug);

        } else {
            SugHistoryPreferences.saveGoWhereSugHistory(activity, sug);
        }
    }

    private ArrayList<TextInputSug> getHistoryList() {
        Activity activity = getActivity();
        if (activity == null) {
            return null;
        }

        if (mType == TYPE_FROM_WHERE) {
            return SugHistoryPreferences.getFromWhereHistoryList(activity);
        } else {
            return SugHistoryPreferences.getGoWhereHistoryList(activity);
        }
    }

    private void clearPreferenceHistory() {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }

        if (mType == TYPE_FROM_WHERE) {
            SugHistoryPreferences.clearPreferenceFromWhereHistory(activity);
        } else {
            SugHistoryPreferences.clearPreferenceGoWhereHistory(activity);
        }
    }

    public static String splitAndFilterString(String input) {
        return Html.fromHtml(input).toString();
    }

}
